<template>
  <div class="box contenBox locationAdd">
    <div class="divForm">
      <el-form
        :model="form"
        :rules="rules"
        ref="ruleForm"
        class="demo-ruleForm"
        v-loading="loading"
      >
        <el-row :gutter="30">
          <el-col :span="6">
            <el-form-item label="库区" prop="location">
              <el-cascader  v-model="form.location"
                            @change="handleItemChange"
                            :props="cascaderOptions.props"
                            clearable
                            style="width:100%"
                            v-if="cascaderOptionsFlag"
              >
              </el-cascader>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="库位编号" prop="code">
              <el-input
                v-model="form.code"
                placeholder="请输入"
                clearable
                disabled="disabled"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="库位名称" prop="name">
                <el-input
                  v-model="form.name"
                  placeholder="请输入"
                  clearable
                  maxlength="10"
                ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="温度类型" prop="temperatureType">
                <el-select
                  v-model="form.temperatureType"
                  placeholder="请选择"
                  style="width: 100%"
                  clearable
                >
                  <el-option
                    v-for="item in temperatureTypeOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  ></el-option>
                </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="30">
          <el-col :span="6">
            <el-form-item label="承重类型" prop="bearingType">
                <el-select
                  v-model="form.bearingType"
                  placeholder="请选择"
                  style="width: 100%"
                  clearable
                >
                  <el-option
                    v-for="item in bearingTypeOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  ></el-option>
                </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="用途属性" prop="useType">
                <el-select
                  v-model="form.useType"
                  placeholder="请选择"
                  style="width: 100%"
                  clearable
                >
                  <el-option
                    v-for="item in useTypeOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  ></el-option>
                </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="停用状态" prop="status">
                <el-radio-group v-model="form.status">
                  <el-radio label="1">启用</el-radio>
                  <el-radio label="0">停用</el-radio>
                </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="30">
          <el-col :span="6">
            <el-form-item label="承载体积" prop="maxVolume" class="formInfoTip">
                <el-input v-model="form.maxVolume" placeholder="请输入" clearable type="number"
                  ><template slot="append">m³</template></el-input
                >
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="承载上限" prop="maxNum" class="formInfoTip">
                <el-input v-model="form.maxNum" placeholder="请输入" clearable type="number"
                  ><template slot="append">个</template></el-input
                >
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="承载重量" prop="maxWeight" class="formInfoTip">
                <el-input v-model="form.maxWeight" placeholder="请输入" clearable type="number"
                  ><template slot="append">Kg</template></el-input
                >
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="30">
          <el-col :span="12">
            <el-form-item label="库位排/列/层" prop="locationRow">
              <el-row :gutter="30" style="margin-top:30px">
                <el-col :span="8">
                  <el-input
                    v-model="form.locationRow"
                    placeholder="请输入"
                    type="number"
                    clearable
                    @change="locationRowChange"
                  ></el-input>
                </el-col>
                <el-col :span="8">
                  <el-input
                    v-model="form.locationColumn"
                    placeholder="请输入"
                    type="number"
                    clearable
                    @change="locationColumnChange"
                  ></el-input>
                </el-col>
                <el-col :span="8">
                  <el-input
                    v-model="form.locationLayer"
                    placeholder="请输入"
                    type="number"
                    clearable
                  @change="locationLayerChange"
                  ></el-input>
                </el-col>
              </el-row>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="库位长/宽/高" prop="locationLength" class="formInfoTip">
              <el-row :gutter="30" style="margin-top:30px">
                <el-col :span="8">
                  <el-input v-model="form.locationLength" placeholder="请输入" clearable
                  @change="handleBlurLength"
                    type="number"
                    ><template slot="append">cm</template></el-input>
                </el-col>
                <el-col :span="8">
                    <el-input v-model="form.locationWidth" placeholder="请输入" clearable
                    @change="handleBlurWidth"
                      type="number"
                    ><template slot="append">cm</template></el-input>
                </el-col>
                <el-col :span="8">
                    <el-input v-model="form.locationHigh" placeholder="请输入" clearable
                    @change="handleBlurHigh"
                      type="number">
                    <template slot="append">cm</template></el-input
                  >
                </el-col>
              </el-row>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <div class="buttonBox">
      <base-button
        class="unimportanceButton btnReturn"
        @click="btnReturnClick"
      >返回</base-button>
      <base-button
        class="minorImportantButton btnSave"
        @click="btnSaveClick"
      >提交</base-button>
    </div>
  </div>
</template>
<script lang="ts">
import { Component } from 'vue-property-decorator'
import BaseButton from '@/components/base-button/index.vue'
import { getAllAreaList } from '@/module-base/api/area'
import { IWarehouseTableData } from '@/module-base/interface/warehouse'
import { getAllWarehouse } from '@/module-base/api/warehouse'
import { IAreaTableData } from '@/module-base/interface/area'
import { ICommonReturn, ICommonSelectOptionsString } from '@/utils/common-interface'
import { warehouseTypeSelectOptions, temperatureTypeOptions, bearingTypeOptions, useTypeOptions } from '@/utils/common-select-data'
import { generateWarehouseCode } from '@/api/common-api'
import { addLocation, findOneLocation, updateLocation } from '@/module-base/api/location-add'
import { ElForm } from 'element-ui/types/form'
import { mixins } from 'vue-class-component'
import SinglePage from '@/mixin/single-page'
import { isIntegerNotMust, validateFloat, validateInt, validateValidity } from '@/utils/validate'
@Component({
  name: 'LocationeAdd',
  components: {
    BaseButton
  }
})

export default class extends mixins(SinglePage) {
  private form = {
    location: [] as string[], // 可以回显
    code: '',
    name: '',
    temperatureType: '',
    bearingType: '',
    useType: '',
    status: '1',
    maxVolume: null,
    maxNum: null,
    maxWeight: null,
    locationRow: null as any,
    locationColumn: null as any,
    locationLayer: null as any,
    locationLength: null as any,
    locationWidth: null as any,
    locationHigh: null as any
  }

  private rules = {
    location: [{ required: true, message: '请选择库区', trigger: 'change' }],
    name: [{ required: true, message: '请输入库位名称', trigger: 'blur' }],
    temperatureType: [{ required: true, message: '请选择温度类型', trigger: 'change' }],
    bearingType: [{ required: true, message: '请选择承重类型', trigger: 'change' }],
    useType: [{ required: true, message: '请选择用途属性', trigger: 'change' }],
    status: [{ required: true, message: '请选择停用状态', trigger: 'change' }],
    maxVolume: [{ required: true, validator: validateFloat, trigger: 'blur' }],
    maxNum: [
      { required: false, validator: validateInt, trigger: 'blur' }
    ],
    maxWeight: [
      { required: false, validator: validateFloat, trigger: 'blur' }]
  }

  private warehouseTypeOptions: ICommonSelectOptionsString[] = []

  private temperatureTypeOptions:ICommonSelectOptionsString[] = []

  private bearingTypeOptions:ICommonSelectOptionsString[] = []

  private useTypeOptions:ICommonSelectOptionsString[] = []

  // key是string因为id是长整型，转数字会失真
  private areaMap :Map<string, IAreaTableData> = new Map()

  private cascaderOptionsFlag = false

  private cascaderOptions = {
    props: {
      lazy: true,
      lazyLoad: async(node:any, resolve:any) => { // 使用箭头函数来在函数中使用页面的this
        const { level } = node
        if (level === 0) {
          const { data } = await getAllWarehouse({ status: 1 })
          const nodes = data.map((item:IWarehouseTableData) => {
            return {
              value: item.id,
              label: item.name,
              leaf: level >= 1 // 不设置的话点击第一级菜单也会触发change事件  文本区域也会填充
            }
          })
          resolve(nodes)
        } else if (level === 1) {
          const { data } = await getAllAreaList({ warehouseId: node.value, status: 1 })
          let nodes = []
          if (data) {
            nodes = data.map((item:IAreaTableData) => {
              if (item.id) {
                this.areaMap.set(String(item.id), item)
              }
              return {
                value: item.id,
                label: item.name,
                leaf: level >= 1// 不设置的话还会继续加载下一级菜单
              }
            })
          }
          resolve(nodes)
        }
      }
    }
  }

  private loading = false

  private handleItemChange(value:string) {
    // 进行库位默认值和温度类型，城中类型，用途属性联动的操作
    if (Array.isArray(value) && value.length === 2) {
      const obj = this.areaMap.get(value[1])
      if (obj) {
        if (obj.temperatureType) {
          this.form.temperatureType = obj.temperatureType
        }
        if (obj.bearingType) {
          this.form.bearingType = obj.bearingType
        }
        if (obj.useType) {
          this.form.useType = obj.useType
        }
      }
    }
  }

  created() {
    // 只能写在这里，不然库区级联回显就会失败
    this.initData()
  }

  private async initData() {
    this.warehouseTypeOptions = warehouseTypeSelectOptions
    this.temperatureTypeOptions = temperatureTypeOptions
    this.bearingTypeOptions = bearingTypeOptions
    this.useTypeOptions = useTypeOptions
    const id = this.$route.params.id
    this.loading = true
    if (id === 'null') {
      // 新增操作
      const { data } = await generateWarehouseCode('KW')
      this.form.code = data
    } else {
      // 修改操作
      const { data } = await findOneLocation(id)
      this.form = {
        ...data,
        status: String(data.status),
        location: [data.warehouseId, data.areaId]
      }
    }
    this.cascaderOptionsFlag = true
    this.loading = false
  }

  private btnReturnClick() {
    this.$router.go(-1)
  }

  private btnSaveClick() {
    (this.$refs.ruleForm as ElForm).validate(async(valid: boolean) => {
      if (valid) {
        const form = this.form
        const params = {
          ...form,
          warehouseId: form.location[0],
          areaId: form.location[1]
        }
        let data: ICommonReturn
        if (this.$route.params.id === 'null') {
          // 新增操作
          data = ((await addLocation(params)) as unknown) as ICommonReturn
        } else {
          data = ((await updateLocation(params)) as unknown) as ICommonReturn
        }
        if (data.code === 0) {
          this.$message({
            showClose: true,
            message: '恭喜你，提交成功！',
            type: 'success'
          })
          this.closeWindow()
        } else {
          this.$message({
            showClose: true,
            message: data.msg,
            type: 'error'
          })
        }
      } else {
        return false
      }
    })
  }

  handleBlurLength(newVal: any) {
    const error = this.$message
    this.form.locationLength = validateValidity(newVal, error)
  }

  handleBlurWidth(newVal: any) {
    const error = this.$message
    this.form.locationWidth = validateValidity(newVal, error)
  }

  handleBlurHigh(newVal: any) {
    const error = this.$message
    this.form.locationHigh = validateValidity(newVal, error)
  }

  locationRowChange(newVal: any) {
    if (newVal && isIntegerNotMust(newVal)) {
      let num = parseInt(newVal, 10)
      if (num > 999999999) {
        num = 999999999
        this.$message.error('库位排只能是正整数')
      }
      this.form.locationRow = num
    } else {
      this.$message.error('库位排只能是正整数')
      this.form.locationRow = Number(newVal).toFixed(2)
    }
  }

  locationColumnChange(newVal: any) {
    if (newVal && isIntegerNotMust(newVal)) {
      let num = parseInt(newVal, 10)
      if (num > 999999999) {
        num = 999999999
        this.$message.error('库位列只能是正整数')
      }
      this.form.locationColumn = num
    } else {
      this.$message.error('库位列只能是正整数')
      this.form.locationColumn = Number(newVal).toFixed(2)
    }
  }

  locationLayerChange(newVal: any) {
    if (newVal && isIntegerNotMust(newVal)) {
      let num = parseInt(newVal, 10)
      if (num > 999999999) {
        num = 999999999
        this.$message.error('库位层只能是正整数')
      }
      this.form.locationLayer = num
    } else {
      this.$message.error('库位层只能是正整数')
      this.form.locationLayer = Number(newVal).toFixed(2)
    }
  }
}
</script>

<style lang="scss" scoped>
@import './index.scss';
</style>
<style lang="scss">
</style>
